import os
import tomllib
import sys
import copy

configs: dict = {}

# 初始化配置目录
if (not os.path.exists("config")):
    os.mkdir("config")
if (not os.path.exists("config"+os.sep+"session")):
    os.mkdir("config"+os.sep+"session")
with open("version", "r") as file:
    version = file.read()
work_dir = os.getcwd()


def load_configs() -> None:  # 加载配置
    global configs
    with open(os.path.dirname(__file__)+os.sep+"config_template.toml", "rb") as file:
        configs = tomllib.load(file)

    origin_cfg = copy.deepcopy(configs)

    if (os.path.exists("config"+os.sep+"config.toml")):
        with open("config"+os.sep+"config.toml", "rb") as file:
            for i, j in tomllib.load(file).items():
                configs[i].update(j)

    # 读取命令行参数
    for i in sys.argv:
        if (i.startswith("--set-config:")):
            cfg_key = i.split("=")[0].replace("--set-config:", "")
            cfg_val = i.split("=")[1]
            cfg_pointer_now = configs
            cfg_pointer_old = origin_cfg
            for j in cfg_key.split(".")[:-1]:
                if (j not in cfg_pointer_now):
                    cfg_pointer_now[j] = {}
                if (j not in cfg_pointer_old):
                    cfg_pointer_old[j] = {}
                cfg_pointer_now = cfg_pointer_now[j]
                cfg_pointer_old = cfg_pointer_old[j]
            try:
                eval_var = __import__("ast").literal_eval(cfg_val)
            except:
                eval_var = cfg_val
            if (cfg_key.split(
                    ".")[-1]) in cfg_pointer_old:
                eval_var = type(cfg_pointer_old[cfg_key.split(
                    ".")[-1]])(eval_var)
            print("::> Rewrite \""+cfg_key+"\" => " +
                  repr(eval_var))
            cfg_pointer_now[cfg_key.split(
                ".")[-1]] = eval_var  # type: ignore
        if (i.startswith("--add-config:")):
            cfg_key = i.split("=")[0].replace("--add-config:", "")
            cfg_val = i.split("=")[1]
            cfg_pointer_now = configs
            for j in cfg_key.split("."):
                if (j not in cfg_pointer_now):
                    cfg_pointer_now[j] = {}
                cfg_pointer_now = cfg_pointer_now[j]
            try:
                eval_var = __import__("ast").literal_eval(cfg_val)
            except:
                eval_var = cfg_val
            print("::> Add \""+cfg_key+"\" + "+repr(eval_var))
            cfg_pointer_now.append(eval_var)  # type: ignore


def read(config_name: str) -> dict:  # 读取配置项目
    global configs
    if len(configs) == 0:
        load_configs()
    return configs[config_name]
